@{
    ViewData["Title"] = "不良品分布";
}

<style>
    /* 页面整体样式 - 简约大气企业级 */
    body {
        background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        font-family: 'Microsoft YaHei', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        margin: 0;
        padding: 0;
    }

    /* 主容器 */
    .defective-container {
        min-height: 100vh;
        padding: 24px;
        background: transparent;
    }

    /* 主卡片 */
    .main-card {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);
        border-radius: 16px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
        border: 1px solid rgba(255, 255, 255, 0.2);
        overflow: hidden;
        margin-bottom: 24px;
    }

    /* 页面标题区域 */
    .page-header {
        background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
        color: white;
        padding: 32px 40px;
        position: relative;
        overflow: hidden;
    }

    .page-header::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(45deg, transparent 30%, rgba(255, 255, 255, 0.1) 50%, transparent 70%);
        animation: shimmer 3s ease-in-out infinite;
    }

    .page-title {
        font-size: 28px;
        font-weight: 600;
        margin: 0;
        position: relative;
        z-index: 2;
        letter-spacing: 0.5px;
    }

    .page-subtitle {
        font-size: 14px;
        opacity: 0.9;
        margin: 8px 0 0 0;
        position: relative;
        z-index: 2;
        font-weight: 400;
    }

    /* 搜索区域 */
    .search-section {
        background: #f8fafc;
        border-bottom: 1px solid #e2e8f0;
        padding: 32px 40px;
    }

    .search-form {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: 24px;
        align-items: end;
    }

    .form-group {
        position: relative;
    }

    .form-label {
        display: block;
        font-weight: 500;
        color: #374151;
        margin-bottom: 8px;
        font-size: 14px;
    }

    .form-input {
        width: 100%;
        padding: 12px 16px;
        border: 2px solid #e5e7eb;
        border-radius: 8px;
        font-size: 14px;
        transition: all 0.2s ease;
        background: white;
        color: #374151;
    }

    .form-input:focus {
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        outline: none;
    }

    .form-input::placeholder {
        color: #9ca3af;
    }

    /* 时间选择器组 */
    .time-group {
        display: flex;
        align-items: center;
        background: white;
        border: 2px solid #e5e7eb;
        border-radius: 8px;
        overflow: hidden;
        transition: all 0.2s ease;
    }

    .time-group:focus-within {
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }

    .time-input {
        flex: 1;
        border: none;
        padding: 12px 16px;
        font-size: 14px;
        background: transparent;
        outline: none;
        color: #374151;
    }

    .time-separator {
        padding: 0 16px;
        color: #6b7280;
        font-size: 14px;
        background: #f9fafb;
        border-left: 1px solid #e5e7eb;
        border-right: 1px solid #e5e7eb;
        height: 100%;
        display: flex;
        align-items: center;
        white-space: nowrap;
    }

    /* 按钮样式 */
    .btn {
        padding: 12px 24px;
        border: none;
        border-radius: 8px;
        font-weight: 500;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.2s ease;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        position: relative;
        overflow: hidden;
        min-width: 100px;
        justify-content: center;
    }

    .btn::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
        transition: left 0.3s ease;
    }

    .btn:hover::before {
        left: 100%;
    }

    .btn-primary {
        background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
        color: white;
    }

    .btn-primary:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
    }

    .btn-secondary {
        background: #f3f4f6;
        color: #374151;
        border: 2px solid #e5e7eb;
    }

    .btn-secondary:hover {
        background: #e5e7eb;
        border-color: #d1d5db;
        transform: translateY(-1px);
    }

    .btn-success {
        background: linear-gradient(135deg, #059669 0%, #10b981 100%);
        color: white;
    }

    .btn-success:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
    }

    /* 操作按钮区域 */
    .action-buttons {
        display: flex;
        gap: 16px;
        flex-wrap: wrap;
        margin: 24px 40px;
    }

    /* 表格容器 */
    .table-container {
        padding: 0 40px 40px;
    }

    /* 表格样式 */
    .layui-table {
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        border: 1px solid #e5e7eb;
    }

    .layui-table thead tr {
        background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
        color: white;
    }

    .layui-table thead th {
        border: none;
        padding: 16px 12px;
        font-weight: 600;
        font-size: 14px;
        text-align: center;
    }

    .layui-table tbody tr {
        transition: all 0.2s ease;
        border-bottom: 1px solid #f3f4f6;
    }

    .layui-table tbody tr:hover {
        background: #f8fafc;
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .layui-table tbody td {
        padding: 16px 12px;
        border: none;
        font-size: 14px;
        color: #374151;
        text-align: center;
    }

    /* 占比徽章样式 */
    .percentage-badge {
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
        text-align: center;
        min-width: 60px;
        display: inline-block;
    }

    .percentage-high {
        background: linear-gradient(135deg, #dc2626 0%, #ef4444 100%);
        color: white;
    }

    .percentage-medium {
        background: linear-gradient(135deg, #ea580c 0%, #f97316 100%);
        color: white;
    }

    .percentage-low {
        background: linear-gradient(135deg, #059669 0%, #10b981 100%);
        color: white;
    }

    .percentage-none {
        background: #f3f4f6;
        color: #6b7280;
    }

    /* 分页样式 */
    .layui-table-page {
        margin-top: 24px;
        text-align: center;
    }

    .layui-laypage {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        background: white;
        padding: 12px 20px;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        border: 1px solid #e5e7eb;
    }

    .layui-laypage a,
    .layui-laypage span {
        padding: 8px 12px;
        border-radius: 6px;
        transition: all 0.2s ease;
        text-decoration: none;
        color: #374151;
        font-weight: 500;
        border: 1px solid transparent;
    }

    .layui-laypage a:hover {
        background: #f3f4f6;
        color: #1e40af;
        border-color: #dbeafe;
    }

    .layui-laypage .layui-laypage-curr {
        background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
        color: white;
        box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
    }

    /* 列设置弹窗样式 */
    .column-settings-modal {
        background: white;
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
    }

    .modal-header {
        background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
        color: white;
        padding: 24px 32px;
        position: relative;
    }

    .modal-header h3 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
    }

    .modal-header p {
        margin: 8px 0 0 0;
        opacity: 0.9;
        font-size: 14px;
    }

    .modal-body {
        padding: 32px;
    }

    .modal-footer {
        background: #f8fafc;
        padding: 24px 32px;
        text-align: center;
        border-top: 1px solid #e5e7eb;
        display: flex;
        justify-content: flex-end;
        gap: 12px;
    }

    /* 拖拽相关样式 */
    .draggable-row {
        transition: all 0.2s ease;
        border-radius: 8px;
        margin-bottom: 4px;
    }

    .draggable-row:hover {
        background: #f8fafc;
        transform: translateX(4px);
    }

    .drag-handle {
        user-select: none;
        transition: all 0.2s ease;
        padding: 8px;
        border-radius: 6px;
        cursor: move;
    }

    .drag-handle:hover {
        background: #dbeafe;
        color: #1e40af;
    }

    .ui-sortable-helper {
        background: white;
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        border-radius: 8px;
        transform: rotate(1deg);
    }

    .ui-sortable-placeholder {
        background: #f0f9ff;
        border: 2px dashed #3b82f6;
        border-radius: 8px;
        height: 50px;
        margin: 4px 0;
    }

    /* 加载动画 */
    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255, 255, 255, 0.9);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
        opacity: 0;
        visibility: hidden;
        transition: all 0.3s ease;
    }

    .loading-overlay.show {
        opacity: 1;
        visibility: visible;
    }

    .loading-spinner {
        width: 40px;
        height: 40px;
        border: 3px solid #e5e7eb;
        border-top: 3px solid #3b82f6;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    /* 动画定义 */
    @@keyframes shimmer {
        0% {
            transform: translateX(-100%) rotate(45deg);
        }

        100% {
            transform: translateX(100%) rotate(45deg);
        }
    }

    @@keyframes spin {
        0% {
            transform: rotate(0deg);
        }

        100% {
            transform: rotate(360deg);
        }
    }

    /* 响应式设计 */
    @@media (max-width: 768px) {
        .defective-container {
            padding: 16px;
        }

        .page-header {
            padding: 24px 20px;
        }

        .page-title {
            font-size: 24px;
        }

        .search-section {
            padding: 24px 20px;
        }

        .search-form {
            grid-template-columns: 1fr;
            gap: 16px;
        }

        .action-buttons {
            margin: 20px;
            flex-direction: column;
            align-items: stretch;
        }

        .table-container {
            padding: 0 20px 20px;
        }

        .modal-body {
            padding: 20px;
        }
    }

    /* 图标样式 */
    .layui-icon {
        font-size: 16px;
        line-height: 1;
    }

    /* 复选框样式 */
    .layui-form-checkbox[lay-skin="primary"] i {
        border-radius: 4px;
        border-color: #d1d5db;
    }

    .layui-form-checked[lay-skin="primary"] i {
        background-color: #3b82f6;
        border-color: #3b82f6;
    }
</style>

<div class="defective-container">
    <!-- 加载遮罩 -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="loading-spinner"></div>
    </div>

    <div class="main-card">
        <!-- 页面标题 -->
        <div class="page-header">
            <h1 class="page-title">不良品分布</h1>
            <p class="page-subtitle">质量数据分析与统计报告</p>
        </div>

        <!-- 查询表单 -->
        <div class="search-section">
            <form class="search-form" id="searchForm">
                <div class="form-group">
                    <label class="form-label">时间范围</label>
                    <div class="time-group">
                        <input type="text" name="StartTime" id="startTime" placeholder="开始时间" class="time-input"
                            readonly>
                        <div class="time-separator">至</div>
                        <input type="text" name="EndTime" id="endTime" placeholder="结束时间" class="time-input" readonly>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">不良品项编号</label>
                    <input type="text" name="DefectiveItemCode" placeholder="请输入编号" class="form-input">
                </div>

                <div class="form-group">
                    <label class="form-label">不良品项名称</label>
                    <input type="text" name="DefectiveItemName" placeholder="请输入名称" class="form-input">
                </div>

                <div class="form-group">
                    <label class="form-label">&nbsp;</label>
                    <div style="display: flex; gap: 12px;">
                        <button type="button" class="btn btn-primary" id="queryBtn">
                            <i class="layui-icon layui-icon-search"></i>
                            查询
                        </button>
                        <button type="reset" class="btn btn-secondary">
                            <i class="layui-icon layui-icon-refresh"></i>
                            重置
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
            <button class="btn btn-success" id="exportBtn">
                <i class="layui-icon layui-icon-export"></i>
                导出数据
            </button>
            <button class="btn btn-secondary" id="refreshBtn">
                <i class="layui-icon layui-icon-refresh-1"></i>
                刷新数据
            </button>
            <button class="btn btn-secondary" id="columnBtn">
                <i class="layui-icon layui-icon-set"></i>
                显示列设置
            </button>
        </div>

        <!-- 表格容器 -->
        <div class="table-container">
            <table class="layui-table" id="defectiveItemTable" lay-filter="defectiveItemTable"></table>
        </div>
    </div>
</div>

<!-- 占比模板 -->
<script type="text/html" id="percentageTpl">
    {{# if(d.percentage !== undefined && d.percentage !== null) { }}
        <span class="percentage-badge {{d.percentage > 10 ? 'percentage-high' : d.percentage > 5 ? 'percentage-medium' : 'percentage-low'}}">
            {{d.percentage.toFixed(2)}}%
        </span>
    {{# } else { }}
        <span class="percentage-badge percentage-none">-</span>
    {{# } }}
</script>

<!-- 时间模板 -->
<script type="text/html" id="timeTpl">
    {{# if(d.time) { }}
        <span style="color: #6b7280; font-size: 13px;">{{ layui.util.toDateString(d.time, 'yyyy-MM-dd') }}</span>
    {{# } else { }}
        <span style="color: #9ca3af;">-</span>
    {{# } }}
</script>

<!-- 列设置弹窗 -->
<div id="columnSettingsModal" style="display: none;">
    <div class="column-settings-modal">
        <div class="modal-header">
            <h3>显示列设置</h3>
            <p>选择要显示的表格列，拖动可调整顺序</p>
        </div>
        <div class="modal-body">
            <table class="layui-table" id="columnSettingsTable">
                <thead>
                    <tr>
                        <th width="60">#</th>
                        <th>列名</th>
                        <th width="100">是否显示</th>
                    </tr>
                </thead>
                <tbody id="columnSettingsBody">
                    <tr data-field="time" class="draggable-row">
                        <td>1</td>
                        <td class="drag-handle" style="cursor: move;">
                            <i class="layui-icon layui-icon-drag" style="margin-right: 8px; color: #9ca3af;"></i>
                            时间
                        </td>
                        <td><input type="checkbox" name="time" lay-skin="primary" title="显示" checked></td>
                    </tr>
                    <tr data-field="defectiveItemCode" class="draggable-row">
                        <td>2</td>
                        <td class="drag-handle" style="cursor: move;">
                            <i class="layui-icon layui-icon-drag" style="margin-right: 8px; color: #9ca3af;"></i>
                            不良品项编号
                        </td>
                        <td><input type="checkbox" name="defectiveItemCode" lay-skin="primary" title="显示" checked></td>
                    </tr>
                    <tr data-field="defectiveItemName" class="draggable-row">
                        <td>3</td>
                        <td class="drag-handle" style="cursor: move;">
                            <i class="layui-icon layui-icon-drag" style="margin-right: 8px; color: #9ca3af;"></i>
                            不良品项名称
                        </td>
                        <td><input type="checkbox" name="defectiveItemName" lay-skin="primary" title="显示" checked></td>
                    </tr>
                    <tr data-field="quantity" class="draggable-row">
                        <td>4</td>
                        <td class="drag-handle" style="cursor: move;">
                            <i class="layui-icon layui-icon-drag" style="margin-right: 8px; color: #9ca3af;"></i>
                            数量
                        </td>
                        <td><input type="checkbox" name="quantity" lay-skin="primary" title="显示" checked></td>
                    </tr>
                    <tr data-field="totalQuantity" class="draggable-row">
                        <td>5</td>
                        <td class="drag-handle" style="cursor: move;">
                            <i class="layui-icon layui-icon-drag" style="margin-right: 8px; color: #9ca3af;"></i>
                            总数量
                        </td>
                        <td><input type="checkbox" name="totalQuantity" lay-skin="primary" title="显示" checked></td>
                    </tr>
                    <tr data-field="percentage" class="draggable-row">
                        <td>6</td>
                        <td class="drag-handle" style="cursor: move;">
                            <i class="layui-icon layui-icon-drag" style="margin-right: 8px; color: #9ca3af;"></i>
                            占比
                        </td>
                        <td><input type="checkbox" name="percentage" lay-skin="primary" title="显示" checked></td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" id="cancelColumnSettings">取消</button>
            <button class="btn btn-secondary" id="resetColumnSettings">重置</button>
            <button class="btn btn-primary" id="confirmColumnSettings">确定</button>
        </div>
    </div>
</div>

@section Scripts {
    <!-- 引入jQuery UI库支持拖拽功能 -->
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">

    <script>
        layui.use(['table', 'form', 'layer', 'laydate', 'laypage'], function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var laydate = layui.laydate;
            var laypage = layui.laypage;

            // 初始化时间选择器
            laydate.render({
                elem: '#startTime',
                type: 'date',
                theme: '#3b82f6',
                done: function (value) {
                    console.log('开始时间选择:', value);
                }
            });

            laydate.render({
                elem: '#endTime',
                type: 'date',
                theme: '#3b82f6',
                done: function (value) {
                    console.log('结束时间选择:', value);
                }
            });

            // 初始化不良品项分布表格
            initDefectiveItemTable(table, layer);

            // 查询按钮点击事件 - 根据表单条件筛选数据
            $('#queryBtn').click(function () {
                showLoading();
                var queryParams = {};

                // 收集表单中的查询条件
                var startTime = $('#startTime').val();
                var endTime = $('#endTime').val();
                var defectiveItemCode = $('input[name="DefectiveItemCode"]').val();
                var defectiveItemName = $('input[name="DefectiveItemName"]').val();

                // 只添加有值的参数
                if (startTime) queryParams.StartTime = startTime;
                if (endTime) queryParams.EndTime = endTime;
                if (defectiveItemCode) queryParams.DefectiveItemCode = defectiveItemCode;
                if (defectiveItemName) queryParams.DefectiveItemName = defectiveItemName;

                console.log('查询参数:', queryParams);

                // 重新加载表格数据
                table.reload('defectiveItemTable', {
                    where: queryParams,
                    page: { curr: 1 }
                });

                hideLoading();
            });

            // 导出按钮点击事件
            $('#exportBtn').click(function () {
                showLoading();
                setTimeout(function () {
                    exportDefectiveItemData();
                    hideLoading();
                }, 1000);
            });

            // 刷新数据按钮点击事件 - 清空条件重新加载所有数据
            $('#refreshBtn').click(function () {
                showLoading();

                // 清空表单
                $('#searchForm')[0].reset();
                $('#startTime').val('');
                $('#endTime').val('');

                console.log('刷新数据 - 清空所有查询条件');

                // 重新加载表格数据（无查询条件）
                table.reload('defectiveItemTable', {
                    where: {},
                    page: { curr: 1 }
                });

                hideLoading();
            });

            // 显示列按钮点击事件
            $('#columnBtn').click(function () {
                showColumnSettings();
            });

            // 显示加载动画
            function showLoading() {
                document.getElementById('loadingOverlay').classList.add('show');
            }

            // 隐藏加载动画
            function hideLoading() {
                document.getElementById('loadingOverlay').classList.remove('show');
            }
        });

        // 初始化不良品项分布表格
        function initDefectiveItemTable(table, layer) {
            table.render({
                elem: '#defectiveItemTable',
                url: '@Url.Action("GetDefectiveItemDistributionPage", "DefectiveItemDistribution")',
                method: 'get',
                where: getSearchParams(),
                page: {
                    layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                    groups: 3,
                    first: '首页',
                    last: '尾页',
                    theme: '#3b82f6'
                },
                limit: 10,
                limits: [5, 10, 20, 50, 100],
                height: 'auto',
                size: 'lg',
                loading: true,
                text: {
                    none: '<div style="padding: 30px; text-align: center; color: #9ca3af;"><i class="layui-icon layui-icon-face-cry" style="font-size: 48px; margin-bottom: 10px;"></i><br>暂无相关数据</div>'
                },
                parseData: function (res) {
                    console.log('不良品项分布表格原始数据:', res);
                    return {
                        "code": res.code || 0,
                        "msg": res.msg || "",
                        "count": res.count || res.TotaCount || 0,
                        "data": res.data || res.PageData || []
                    };
                },
                cols: [[
                    { type: 'numbers', title: '序号', width: 80, fixed: 'left' },
                    { field: 'time', title: '时间', width: 120, templet: '#timeTpl', align: 'center' },
                    { field: 'defectiveItemCode', title: '不良品项编号', minWidth: 200 },
                    { field: 'defectiveItemName', title: '不良品项名称', minWidth: 200 },
                    { field: 'quantity', title: '数量', width: 100, align: 'center' },
                    { field: 'totalQuantity', title: '总数量', width: 100, align: 'center' },
                    { field: 'percentage', title: '占比', width: 120, templet: '#percentageTpl', align: 'center' }
                ]],
                done: function (res, curr, count) {
                    console.log('表格渲染完成:', res, curr, count);
                    updatePageTitle(count);

                    if (res.code !== 0) {
                        layer.msg('获取数据失败: ' + res.msg, { icon: 2 });
                    }
                },
                error: function (res) {
                    console.error('表格加载失败:', res);
                    layer.msg('表格加载失败', { icon: 2 });
                }
            });
        }

        // 获取查询参数
        function getSearchParams() {
            var params = {};
            $('#searchForm').serializeArray().forEach(function (item) {
                if (item.value) {
                    params[item.name] = item.value;
                }
            });
            return params;
        }

        // 加载不良品项分布数据
        function loadDefectiveItemData(page, params, table) {
            table.reload('defectiveItemTable', {
                where: params,
                page: {
                    curr: page
                }
            });
        }

        // 更新页面标题
        function updatePageTitle(count) {
            $('.page-subtitle').text('质量数据分析与统计报告 - 共 ' + count + ' 条记录');
        }

        // 导出不良品项分布数据
        function exportDefectiveItemData() {
            var params = getSearchParams();
            params.export = true;

            var queryString = Object.keys(params).map(function (key) {
                return key + '=' + encodeURIComponent(params[key]);
            }).join('&');

            var url = '@Url.Action("GetDefectiveItemDistributionPage", "DefectiveItemDistribution")?' + queryString;

            var link = document.createElement('a');
            link.href = url;
            link.download = '不良品项分布_' + new Date().toISOString().slice(0, 10) + '.csv';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            layer.msg('导出成功', { icon: 1 });
        }

        // 列设置相关变量
        var columnSettings = {
            time: { visible: true, order: 1 },
            defectiveItemCode: { visible: true, order: 2 },
            defectiveItemName: { visible: true, order: 3 },
            quantity: { visible: true, order: 4 },
            totalQuantity: { visible: true, order: 5 },
            percentage: { visible: true, order: 6 }
        };

        // 列配置定义
        var columnConfigs = {
            time: { field: 'time', title: '时间', width: 120, templet: '#timeTpl', align: 'center' },
            defectiveItemCode: { field: 'defectiveItemCode', title: '不良品项编号', minWidth: 200 },
            defectiveItemName: { field: 'defectiveItemName', title: '不良品项名称', minWidth: 200 },
            quantity: { field: 'quantity', title: '数量', width: 100, align: 'center' },
            totalQuantity: { field: 'totalQuantity', title: '总数量', width: 100, align: 'center' },
            percentage: { field: 'percentage', title: '占比', width: 120, templet: '#percentageTpl', align: 'center' }
        };

        // 显示列设置弹窗
        function showColumnSettings() {
            updateCheckboxStates();
            updateColumnOrder();

            layer.open({
                type: 1,
                title: false,
                closeBtn: 1,
                shade: 0,
                shadeClose: false,
                area: ['500px', '450px'],
                content: $('#columnSettingsModal'),
                success: function (layero, index) {
                    layui.form.render();
                    bindColumnSettingsEvents(index);
                    initDragAndDrop();
                }
            });
        }

        // 更新复选框状态
        function updateCheckboxStates() {
            $('#columnSettingsTable input[type="checkbox"]').each(function () {
                var field = $(this).attr('name');
                $(this).prop('checked', columnSettings[field].visible);
            });
        }

        // 更新列顺序显示
        function updateColumnOrder() {
            var sortedFields = Object.keys(columnSettings).sort(function (a, b) {
                return columnSettings[a].order - columnSettings[b].order;
            });

            var tbody = $('#columnSettingsBody');
            tbody.empty();

            sortedFields.forEach(function (field, index) {
                var setting = columnSettings[field];
                var row = `
                            <tr data-field="${field}" class="draggable-row">
                                <td>${index + 1}</td>
                                <td class="drag-handle" style="cursor: move;">
                                    <i class="layui-icon layui-icon-drag" style="margin-right: 8px; color: #9ca3af;"></i>
                                    ${getColumnTitle(field)}
                                </td>
                                <td><input type="checkbox" name="${field}" lay-skin="primary" title="显示" ${setting.visible ? 'checked' : ''}></td>
                            </tr>
                        `;
                tbody.append(row);
            });
        }

        // 获取列标题
        function getColumnTitle(field) {
            var titles = {
                'time': '时间',
                'defectiveItemCode': '不良品项编号',
                'defectiveItemName': '不良品项名称',
                'quantity': '数量',
                'totalQuantity': '总数量',
                'percentage': '占比'
            };
            return titles[field] || field;
        }

        // 初始化拖拽功能
        function initDragAndDrop() {
            $('#columnSettingsBody').sortable({
                handle: '.drag-handle',
                axis: 'y',
                opacity: 0.8,
                tolerance: 'pointer',
                helper: function (e, tr) {
                    var $originals = tr.children();
                    var $helper = tr.clone();
                    $helper.children().each(function (index) {
                        $(this).width($originals.eq(index).width());
                    });
                    return $helper;
                },
                update: function (event, ui) {
                    updateColumnOrderAfterDrag();
                }
            });
        }

        // 拖拽后更新列顺序
        function updateColumnOrderAfterDrag() {
            $('#columnSettingsBody tr').each(function (index) {
                var field = $(this).data('field');
                if (field && columnSettings[field]) {
                    columnSettings[field].order = index + 1;
                }
                $(this).find('td:first').text(index + 1);
            });
        }

        // 绑定列设置事件
        function bindColumnSettingsEvents(layerIndex) {
            $('#cancelColumnSettings').off('click').on('click', function () {
                layer.close(layerIndex);
            });

            $('#resetColumnSettings').off('click').on('click', function () {
                columnSettings = {
                    time: { visible: true, order: 1 },
                    defectiveItemCode: { visible: true, order: 2 },
                    defectiveItemName: { visible: true, order: 3 },
                    quantity: { visible: true, order: 4 },
                    totalQuantity: { visible: true, order: 5 },
                    percentage: { visible: true, order: 6 }
                };
                updateCheckboxStates();
                updateColumnOrder();
                layui.form.render();
            });

            $('#confirmColumnSettings').off('click').on('click', function () {
                // 更新可见性设置
                $('#columnSettingsTable input[type="checkbox"]').each(function () {
                    var field = $(this).attr('name');
                    if (columnSettings[field]) {
                        columnSettings[field].visible = $(this).prop('checked');
                    }
                });

                // 保存设置到localStorage
                localStorage.setItem('defectiveItemColumnSettings', JSON.stringify(columnSettings));

                reloadTableWithColumnSettings();
                layer.close(layerIndex);
                layer.msg('列设置已更新', { icon: 1 });
            });
        }

        // 根据列设置重新渲染表格
        function reloadTableWithColumnSettings() {
            var newCols = [
                { type: 'numbers', title: '序号', width: 80, fixed: 'left' }
            ];

            // 按顺序添加可见的列
            var sortedFields = Object.keys(columnSettings).sort(function (a, b) {
                return columnSettings[a].order - columnSettings[b].order;
            });

            sortedFields.forEach(function (field) {
                if (columnSettings[field].visible && columnConfigs[field]) {
                    newCols.push(columnConfigs[field]);
                }
            });

            layui.table.reload('defectiveItemTable', {
                cols: [newCols]
            });
        }

        // 页面加载完成后初始化
        $(document).ready(function () {
            // 加载保存的列设置
            loadSavedColumnSettings();

            // 添加快捷键支持
            $(document).keydown(function (e) {
                if (e.keyCode === 116) { // F5键刷新
                    e.preventDefault();
                    $('#refreshBtn').click();
                }
                if (e.keyCode === 27) { // ESC键关闭所有弹窗
                    layer.closeAll();
                }
            });
        });

        // 加载保存的列设置
        function loadSavedColumnSettings() {
            var savedSettings = localStorage.getItem('defectiveItemColumnSettings');
            if (savedSettings) {
                try {
                    var saved = JSON.parse(savedSettings);
                    // 合并保存的设置，保持默认值作为后备
                    Object.keys(saved).forEach(function (field) {
                        if (columnSettings[field]) {
                            columnSettings[field].visible = saved[field].visible !== undefined ? saved[field].visible : columnSettings[field].visible;
                            columnSettings[field].order = saved[field].order !== undefined ? saved[field].order : columnSettings[field].order;
                        }
                    });
                } catch (error) {
                    console.error('加载列设置失败:', error);
                }
            }
        }
    </script>
}
